package com.yugao.fintech.antelope.auth.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.yugao.fintech.antelope.auth.constants.CacheKeyEnum;
import com.yugao.fintech.antelope.auth.model.rqrs.CaptchaResp;
import com.yugao.fintech.antelope.auth.service.CaptchaService;
import com.yugao.fintech.antelope.base.model.constants.CommonCons;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.assistant.utils.UUIDUtils;
import com.yugao.fintech.framework.cache.core.service.CacheService;
import com.yugao.fintech.framework.core.response.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 验证码实现处理
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成验证码
     */
    @Override
    public Resp<CaptchaResp> createCaptcha() {
        // 保存验证码信息
        String uuid = UUIDUtils.simpleUUID();

        //定义图形验证码的长和宽 // 4位验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(137, 40, 4, 80);
        lineCaptcha.createCode(); //生成code

        CacheKeyEnum captcha = CacheKeyEnum.CAPTCHA;
        cacheService.opsForValue().setEx(captcha.formatKey(uuid), lineCaptcha.getCode(), captcha.getExpire(), captcha.getUnit());

        CaptchaResp captchaResp = new CaptchaResp();
        captchaResp.setUuid(uuid);
        captchaResp.setImg(CommonCons.IMAGE_BASE64_PRE + lineCaptcha.getImageBase64());

        log.debug("获取验证码, uuid: {}", uuid);
        return Resp.ok(captchaResp);
    }

    /**
     * 校验验证码
     */
    @Override
    public boolean checkCaptcha(String captcha, String uuid) {
        Object result = redisTemplate.opsForValue().get(CacheKeyEnum.CAPTCHA.formatKey(uuid));
        if (StringUtils.isEmpty(captcha) || !captcha.equals(result)) {
            log.error("captcha check fail, captcha: {}", captcha);
            this.deleteCaptcha(uuid);
            return false;
        }
        log.debug("captcha check success, captcha: {}", captcha);
        return true;
    }

    @Override
    public void deleteCaptcha(String uuid) {
        redisTemplate.delete(CacheKeyEnum.CAPTCHA.formatKey(uuid));
    }
}
